<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/11/7
 * Time: 15:13
 */

namespace app\api\controller;


use app\common\controller\Api;
use app\common\library\FutureService;
use app\common\model\FutureTrade;
use think\Db;
use think\Exception;
use think\Request;

class Future extends Api
{
    protected $noNeedLogin = ['*'];
    protected $noNeedRight = ['*'];

    public function index()
    {
        $result = \app\common\model\Future::where('status', \app\common\model\Future::IS_OPEN)->select();
        $this->success('', $result);
    }

    /**
     * 期货买涨买跌
     * @throws \Exception
     */
    public function buy()
    {
        try {
            $future_id = $this->request->request('future_id');
            $num = $this->request->request('num');
            $type = $this->request->request('type');
            $validate = new \think\Validate([
                'future_id' => 'require',
                'num' => 'require',
                'type' => 'require|in:1,2',
            ], [
                'future_id.require' => 'future_id not null',
                'num.require' => 'num not null',
                'type.require' => 'type not null',
                'type.in' => 'type not null',
            ]);
            if (!$validate->check($this->request->request())) {
                exception($validate->getError());
            }

            $future = \app\common\model\Future::where('id', $future_id)->find();
            if (empty($future)) {
                exception('Not find');
            }

            $price = FutureService::getInstance()->getComrms($future->symbol);

            $fee = 0;
            $security_deposit = $price->Obj[0]->P * $num * ($future->percent/100);

            $user = \app\common\model\User::where('id', $this->auth->id)->find();
            if ($user && $user->balance < $fee + $security_deposit) {
                exception('Insufficient account balance');
            }


            Db::startTrans();
            try{

                //更改账号余额
                \app\common\model\User::changeBalance($this->auth->id, -($fee + $security_deposit));

                //创建记录
                $createData = [
                    'future_id' => $future_id,
                    'num' => $num,
                    'user_id' => $this->auth->id,
                    'type' => $type,
                    'status' => 0,
                    'buy_price' => $price->Obj[0]->P,
                    'fee' => $fee,
                    'security_deposit' => $security_deposit,
                    'created_at' => time(),
                    'updated_at' => time()
                ];
                $ret = FutureTrade::create($createData);
                if (empty($ret)) {
                    exception('Buy the failure');
                }
                Db::commit();

            } catch (Exception $e) {
                // 回滚事务
                Db::rollback();
            }

            $this->success();
        } catch (Exception $exception) {
            $this->error($exception->getMessage());
        }

    }

    /**
     * 获取期货价格
     * @param Request $request
     * @throws \Exception
     */
    public function price(Request $request)
    {
        try {
            $symbol = $request->request('symbol');
            if (empty($symbol)) {
                exception('symbol not null');
            }
            $response = FutureService::getInstance()->getComrms($symbol);
            $this->success('success', $response->Obj[0]);
        } catch (Exception $exception) {
            $this->error($exception->getMessage());
        }
    }
}